
//
//  ListViewController.m
//  Lovely Food
//
//  Created by 李经纬 on 15/11/27.
//  Copyright © 2015年 李经纬. All rights reserved.
//

#import "ListViewController.h"
#import "CityCell.h"
#import "DiaryCell.h"
#import "DiaryModel.h"
#import "UIImageView+WebCache.h"
#import "cityModel.h"
#import "DiaryDetialViewController.h"
#define KscreenHeight [[UIScreen mainScreen] bounds].size.height
#define KscreenWidth [[UIScreen mainScreen] bounds].size.width
@interface ListViewController ()<UITableViewDataSource,UITableViewDelegate>


@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) NSMutableArray * diaryDataArray;
@end

@implementation ListViewController
- (NSMutableArray *)diaryDataArray
{
    
    if (_diaryDataArray == nil) {
        _diaryDataArray = [NSMutableArray array];
    }
    return _diaryDataArray;
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    //    self.automaticallyAdjustsScrollViewInsets = NO;
    UIView *view = [[UIView alloc] init];
    view.frame = CGRectMake(0, 0, 50, 50);
    UIImageView *logoIamge = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo"]];
    logoIamge.frame = CGRectMake(0, 3, 50, 40);
    [view addSubview:logoIamge];
    self.navigationItem.titleView = view;
    self.view.backgroundColor = [UIColor greenColor];
    

    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KscreenWidth, KscreenHeight) style:(UITableViewStyleGrouped)];
    
    [self.tableView registerClass:[CityCell class] forCellReuseIdentifier:@"CityCell"];
    [self.tableView registerClass:[DiaryCell class] forCellReuseIdentifier:@"DiaryCell"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.view addSubview:self.tableView];
    
    UIView *view1 = [[UIView alloc] init];
    view1.frame = CGRectMake(0, 0, self.view.frame.size.width, 200);
    view1.backgroundColor = [UIColor redColor];
    
    UIImageView * titleImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"MainTitle.jpg"]];
    titleImage.frame = CGRectMake(0, 0, KscreenWidth, 200);
    titleImage.backgroundColor = [UIColor greenColor];
    [view1 addSubview:titleImage];
    
    self.tableView.tableHeaderView = view1;
    
    
    [self loadData];
    // [self getData];
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    
    return 4;
}

//cell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 700;
    } else {
        
        return 400;
        
    }
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        CityCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CityCell" forIndexPath:indexPath];
        
        
        
        return cell;
        
    }else{
        DiaryCell * cellD = [tableView dequeueReusableCellWithIdentifier:@"DiaryCell" forIndexPath:indexPath];
        //取author的值
        DiaryModel * model = self.diaryDataArray[indexPath.row];
        NSDictionary *dic = model.author;
        NSString * header = dic[@"header"];
        
        NSString * uname = dic[@"uname"];
        
        [cellD.userPhotoImage sd_setImageWithURL:[NSURL URLWithString:header]];
        cellD.userNameLabel.text = uname;
        
        //取其他的值
        cellD.titleNameLabel.text = model.name;
        cellD.cityLabel.text = model.city;
        cellD.likeLabel.text = model.vote;
        cellD.troveLabel.text = model.fav;
        [cellD.foodImage sd_setImageWithURL:[NSURL URLWithString:model.cover]];
        return cellD;
    }
}

//分区高度（返回的值决定了头视图变化的范围）
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 10;
    }else{
        return 60;
    }
    
}
// 头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        
        UIView * titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 100)];
        titleView.backgroundColor = [UIColor whiteColor];
        UILabel * title = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 200, 30)];
        title.text = @"精品食记";
        title.textColor = [UIColor blackColor];
        //title.backgroundColor = [UIColor whiteColor];
        [titleView addSubview:title];
        
        UILabel * sign = [[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(title.frame)+5, 200, 30)];
        sign.text = @"吃到念念不忘的记忆";
        sign.textColor = [UIColor grayColor];
        sign.font = [UIFont systemFontOfSize:14];
        //    sign.backgroundColor = [UIColor yellowColor];
        [titleView addSubview:sign];
        
        
        
        
        return titleView;
    }
    
    return nil;
    
}




//DiaryCell解析
-(void)loadData
{
    NSURLSession * session = [NSURLSession sharedSession];
    
    NSURL * url = [NSURL URLWithString:@"http://www.youyuwei.com/api/recommend?app_code=com.youyuwei.yuwei.ios&hardware_model=iPhone5%2C2&app_ver=2.1&sys_ver=9.1&device_type=ios&ywsdk_ver=20131018&open_udid=086035be98bdf57eb36141a1a8b4c010171912b6&start=0&oauth_timestamp=1449393976&device_token=5fedbc3e6bc4a9aa4223bc304eaaf624a464b0cc3222ba15a80106126ed7cf45&x_auth_mode=client_auth&oauth_signature_method=HMAC-SHA1&ver=2&uid=18080&idfa=73BEDD47-7F7A-4DCC-8F35-15111C2264FE&channel_id=App%20Store&oauth_version=1.0&oauth_consumer_key=4&oauth_token=18080_ebbf4985ba91d7e9ed8fecf6105868c7&oauth_signature=UKqBb5V5WYrPRpG1CnENkIsB0w4%3D&debug=0&oauth_nonce=e05f856bbf65ce9be873be083906fb1f"];
    
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
        
        NSDictionary * dict = dic[@"data"];
        NSArray * array = dict[@"list"];
        NSDictionary * dict1 = array[3];
        NSArray * array1 = dict1[@"content"];
        for (NSDictionary * dict2 in array1) {
            
            DiaryModel * m = [[DiaryModel alloc]init];
            [m setValuesForKeysWithDictionary:dict2];
            [self.diaryDataArray addObject:m];
            //NSLog(@"%@",m.city);
        }
        
        NSLog(@"%@", self.diaryDataArray);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];
        });
    }];
    [task resume];
    
}

//diaryCell的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    DiaryDetialViewController * detailVC = [[DiaryDetialViewController alloc]initWithStyle:(UITableViewStyleGrouped)];
    
    detailVC.rowOfCell = indexPath.row;
    
    [self.navigationController pushViewController:detailVC animated:YES];
    
    NSLog(@"%ld", indexPath.row);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
